package com.by.service.impl;

import com.by.bean.Dept;
import com.by.common.crud.BaseServiceImpl;
import com.by.mapper.DeptMapper;
import com.by.query.DeptQuery;
import com.by.service.DeptService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl extends BaseServiceImpl<Dept, DeptMapper> implements DeptService {


    @Override
    public int save(Dept entity) {
        //生成部门编码
        entity.setDeptCode(generateDeptCode(entity.getParentId()));
        return super.save(entity);
    }

    @Override
    public int delete(Serializable id) {
        //查询子部门
        int c = baseMapper.queryChildCount(id);
        if (c > 0)
            return 2;//说明有子部门 不让删除
        return super.delete(id);
    }

    @Override
    public List queryTree() {
        return baseMapper.queryTree(0);
    }

    @Override
    public int updateStatus(int id, int status) {
        return baseMapper.updateStatus(id, status);
    }

    @Override
    public List<Map> queryChildDept(DeptQuery query) {
        return baseMapper.queryChildDept(query);
    }

    /**
     * 生成编码
     *
     * @param parentId
     * @return
     */
    String generateDeptCode(int parentId) {
        //根据父id查询最大编码
        String maxCode = baseMapper.queryMaxCode(parentId);
        if (null == maxCode) {
            //说明在父id为  parentId 时，子部门还没有   子部门的编码就01
            //确认父编码
            if (parentId == 0) {
                //说明是添加的顶级部门
                return "101";
            }

            //parentId!=0  查询对应部门的编码
            String parentCode = baseMapper.queryCodeById(parentId);
            return parentCode + "01";
        }

        //如果存在最大编码  101
        Integer tmp = Integer.parseInt(maxCode);
        tmp++;
        return String.valueOf(tmp);
    }
}
